package com.luzhikun.jackson.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.luzhikun.jackson.dao.ProvinceDao;
import com.luzhikun.jackson.entity.Privince;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class QueryServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String json="{}";
        // 获取请求参数
        String proid = request.getParameter("proid");
        System.out.println(proid);
        // 判断proid有值时，调用dao查询数据
        if (proid!=null && proid.trim().length()>0){
            Integer proId=Integer.valueOf(proid);
            ProvinceDao provinceDao=new ProvinceDao();
            Privince privince = provinceDao.queryProvinceNameById(proId);
            // 使用jackson把Provice对象转为json
            ObjectMapper obj=new ObjectMapper();
            json = obj.writeValueAsString(privince);
            System.out.println(json);
        }
        // 把获取的数组通过网络传给ajax中的异步对象，响应结果数据
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out=response.getWriter();
        // 会赋给ajax中responseTest属性
        out.println(json);
        out.flush();
        out.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
